<template>
	<view class="padding">
		<view class="cu-form-group">
			<view class="title">手机号</view>
			<input placeholder="请输入手机号" class="text-left" v-model="form.phone"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">验证码</view>
			<input placeholder="请输入验证码" class="text-left" v-model="form.code"></input>
			<button class='cu-btn bg-green shadow' @tap="getCode">{{!captchaTime?'获取验证码':captchaTime+'秒重新获取'}}</button>
		</view>

		<view class="padding" style="border-top: 1rpx solid #eee;">
			<button class="cu-btn shadow-blur block margin-tb-sm bottom-btn bg-blue" @tap="login">登录</button>
		</view>

	</view>
</template>

<script>
	import {
		loginByPhone,
		getSmsCode
	} from '@/api/login.js'
	import validate from '@/utils/validate.js'
	export default {
		data() {
			return {
				form: {
					phone: '',
					code: '',
				},
				tips: '',
				captchaTime: 0,
				timer: null
			}
		},
		onUnload() {
			if (this.timer) {
				console.log("onUnload" + this.timer)
				clearInterval(this.timer);
			}
		},
		created() {},
		methods: {
			login() {
				if (!this.form.phone) {
					uni.showToast({
						title: '请输入手机号码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!this.form.code) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				loginByPhone(this.form).then(res => {
					let tokenInfo = res.data
					uni.setStorageSync('access_token', tokenInfo.tokenValue);
					uni.setStorageSync('expires_in', tokenInfo.tokenTimeout);
					uni.reLaunch({
						url: '/pages/home/index'
					})
				})

			},
			/**
			 * 发送验证码
			 */
			getCode() {
				if (!this.form.phone) {
					uni.showToast({
						title: '请输入手机号',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (!validate.validateMobile(this.form.phone)) {
					uni.showToast({
						title: '请输入正确的手机号',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if (this.captchaTime > 0) {
					uni.showToast({
						title: '不能重复获取',
						icon: 'none'
					})
					return;
				} else {
					getSmsCode(this.form).then(res => {
						uni.showToast({
							title: '验证码已发送',
							icon: 'none',
							duration: 3000
						});
						// 通知验证码组件内部开始倒计时
						this.captchaTime = 60;
						this.timer = setInterval(() => {
							this.captchaTime--;
							console.log(this.captchaTime)
							if (this.captchaTime < 1) {
								clearInterval(this.timer);
								this.captchaTime = 0
							}
						}, 1000)
					});

				}
			},
		}
	}
</script>

<style>
</style>
